package com.ch.web.config.websocket;

import com.ch.web.enums.UserEnumCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.Session;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class WebSocketService {
    private WebSocketServer webSocketServer;

    @Autowired
    public void setWebSocketServer(WebSocketServer webSocketServer) {
        this.webSocketServer = webSocketServer;
    }

    /**
     * 当发现该账号已经被封禁或者禁用的时候 发送信息到前端
     *
     * @param username
     * @throws IOException
     */
    public void forceDown(String username) {
        try {
            System.out.println(webSocketServer);
            ConcurrentHashMap<String, SessionCode> sessionPools = webSocketServer.getSessionPools();
            Session session = sessionPools.get(username).getSession();
            session.getBasicRemote().sendText(String.valueOf(UserEnumCollection.USER_IS_BLANK.getCode()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void sendAllSession() {
        //代表服务器突然断开 此时 应该取出所有的用户 将它们的用户的在线状态设置为下线
        webSocketServer.broadcast("999");
    }

    public void forceDownByUpdatePassword() {
        webSocketServer.broadcast("888");
    }
}
